package com.bjpowernode.mvc.controller;


import cn.hutool.core.io.FileTypeUtil;
import com.bjpowernode.common.enums.Code;
import com.bjpowernode.db.domain.HeaderImage;
import com.bjpowernode.mvc.model.dto.user.HeaderImageDTO;
import com.bjpowernode.mvc.model.dto.user.SaveHeaderImageDTO;
import com.bjpowernode.mvc.model.response.Response;
import com.bjpowernode.mvc.service.inter.HeaderImageService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController

public class HeaderController {


    private static Map<String, String> fileTypeMap = null;

    static {
        fileTypeMap = new HashMap<>();
        fileTypeMap.put("png", "png");
        fileTypeMap.put("gif", "gif");
        fileTypeMap.put("jpg", "jpg");
        fileTypeMap.put("jpeg", "jpeg");
    }

    @Resource
    private HeaderImageService headerImageService;

    @Value("${dfs.http.url")
    private String DFS_HTTP_URL;

    //上传头像.
    @PostMapping(value = "/upload/header")
    public Response uploadHearImage(@RequestParam("headerFile") MultipartFile headerFile,
                                    @RequestHeader("uid") Integer userId) {
        /*
        头像文件的大小
        图片的类型
        尺寸的限制
         */
        Response response = Response.FAIL();
        try {
            if (!headerFile.isEmpty()) {
                //上传文件,有内容
                long byteSize = headerFile.getSize();
                if (byteSize > 1024 * 1024) {
                    return Response.FAIL(Code.FILE_SIZE_LIMIT_MAX);
                }


                //文件的类型Hutool中的工具类
                String type = FileTypeUtil.getType(headerFile.getInputStream());
                if (!fileTypeMap.containsKey(type)) {
                    return Response.FAIL(Code.FILE_SIZE_TYPE_INVALID);
                }


                //尺寸width,height
                BufferedImage image = ImageIO.read(headerFile.getInputStream());
                int width = image.getWidth();
                int height = image.getHeight();


                if (width > 300 || height > 300) {
                    return Response.FAIL(Code.FILE_WIDTH_HEIGHT_INVALID);
                }


                //查看用户是否有头像

                boolean deleteDB = false;
                HeaderImage headerImage = headerImageService.queryUserId(userId);

                if (headerImage != null) {
                    //有历史头像,删除之前的
                    boolean remove = headerImageService.removeHeaderFromDFS(headerImage.getGroupName(),
                            headerImage.getFileId());


                    if (remove) {
                        deleteDB = headerImageService.deleteDB(userId);

                    }
                }

                //重新上传文件.
                if (deleteDB || headerImage == null) {

                    HeaderImageDTO headerImageDTO = HeaderImageDTO.builder().userId(userId).extName(type)
                            .content(headerFile.getBytes()).size(byteSize)
                            .height(height)
                            .width(width).build();

                    //上传文件到FastDFS
                    SaveHeaderImageDTO saveDto = headerImageService.saveFileFastDFS(headerImageDTO);

                    if (saveDto != null) {
                        //上传成功.

                        //把文件信息和fastdto返回的结果存入数据库
                        headerImageDTO.setGroup(saveDto.getGroup());
                        headerImageDTO.setFieldId(saveDto.getFileId());
                        headerImageService.addHeaderImage(headerImageDTO);


                        //显示头像的地址
                        String url = DFS_HTTP_URL + saveDto.getGroup() + "/" + saveDto.getFileId();

                        response = Response.ok(url);
                    }

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }


}
